package cn.progen.util;

import cn.progen.constant.Config;
import cn.progen.tem.temUrl;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Map;


public class FreemarkerUtil {
    private Configuration configuration = null;
    private String outFilePath;
    private String realPath;

    public FreemarkerUtil(String outFilePath,String name) {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        this.outFilePath=outFilePath;
        this.realPath=name;
    }

    public void createDoc(Map dataMap,String temName) {
        //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
        //这里我们的模板是放在com.havenliu.document.template包下面
        try {
            configuration.setClassForTemplateLoading(this.getClass(),"/cn/progen/tem");
            //configuration.getTemplateLoader().findTemplateSource("Mapper.java.ftl");
        } catch (Exception e2) {
//            try {
//                configuration.setDirectoryForTemplateLoading(new File(Config.FREEMARKER_CONFIG_PATH));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            e2.printStackTrace();
        }

        Template t=null;
        try {
            //test.ftl为要装载的模板
            t = configuration.getTemplate(temName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //输出文档路径及名称
        String allPath=(this.outFilePath+this.realPath);
        File outFile1 = new File(allPath.substring(0,allPath.lastIndexOf("\\")));
        File outFile = new File(this.outFilePath+this.realPath);
        try{
            if(!outFile1 .exists() && !outFile1 .isDirectory())
            {
                Boolean flag=outFile1 .mkdirs();
                if(flag){
                    System.out.println("创建目录:"+outFile1.getPath()+" 成功");
                }else{
                    System.out.println("创建目录:"+outFile1.getPath()+" 失败");
                }
            }
        }catch(Exception e){
            System.out.println("创建目录:"+outFile1.getPath());
            outFile1 .mkdirs();
        }
        Writer out = null;
        try {
            //outFile.createNewFile();
            System.out.println("创建文件:"+outFile.getPath());
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            t.process(dataMap, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
